package com.example.demo.aws3;

import com.amazonaws.*;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import com.sun.prism.shader.Solid_TextureYV12_AlphaTest_Loader;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.nio.channels.Pipe;

/**
 * aws 测试
 */
public class XskyDemo {

    public static void main(String[] args) throws Exception {

        /*String server_url = "115.238.54.16";
        AmazonS3 s3client = null;
        //设置连接时的参数
        ClientConfiguration config = new ClientConfiguration();
        //设置连接方式为HTTP，可选参数为HTTP和HTTPS
        config.setProtocol(Protocol.HTTP);
        //config.setProtocol(Protocol.HTTPS);
        //设置网络访问超时时间
        config.setConnectionTimeout(30000);
        config.setUseExpectContinue(true);
        //获取访问凭证
        AWSCredentials credentials = null;
        credentials = new BasicAWSCredentials("O7ODIFP1DEBOK66ZMU73", "z4jJ0Pqe4xHiX2JWt4qiAMMvCpsesKhdEshgjkBs");
        //设置Endpoint
        AwsClientBuilder.EndpointConfiguration end_point = null;
        end_point = new AwsClientBuilder.EndpointConfiguration(server_url, "");
        //创建连接
        s3client = AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withClientConfiguration(config)
                .withEndpointConfiguration(end_point)
                .withPathStyleAccessEnabled(true)
                .build();*/


        System.out.println(FilenameUtils.getExtension("sssss.jpg"));
        System.out.println("sssss.jpg".substring("sssss.jpg".lastIndexOf(".")).toLowerCase());

        AmazonS3 s3client;
        //设置连接时的参数
        ClientConfiguration config = new ClientConfiguration();
        //设置连接方式为HTTP，可选参数为HTTP和HTTPS
        config.setProtocol(Protocol.HTTP);
        //config.setProtocol(Protocol.HTTPS);
        //设置网络访问超时时间
        config.setConnectionTimeout(30000);
        config.setUseExpectContinue(true);
        //获取访问凭证
        AWSCredentials credentials;
        credentials = new BasicAWSCredentials("O7ODIFP1DEBOK66ZMU73", "z4jJ0Pqe4xHiX2JWt4qiAMMvCpsesKhdEshgjkBs");
        //设置Endpoint
        AwsClientBuilder.EndpointConfiguration end_point;
        end_point = new AwsClientBuilder.EndpointConfiguration("115.238.54.16", Strings.EMPTY);
        //创建连接
        s3client = AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withClientConfiguration(config)
                .withEndpointConfiguration(end_point)
                .withPathStyleAccessEnabled(true)
                .build();

        String bucketName = "51pla";
        String filePath = "D:\\csf111.mp4";
        String key = "upload/video/2020/0518/1110/101.mp4";
        String contentType = "video/mp4;video/mpeg;video/quicktime;video/x-m4v;video/x-ms-wmv;video/x-msvideo;video/webm;video/x-flv;application/x-mpegURL;video/MP2T;video/3gpp";

        //XskyS3Bucket xskyS3Bucket = new XskyS3Bucket(s3client);
        //xskyS3Bucket.ListBuckets();

        //putObjectRequest(s3client, bucketName, key, filePath, contentType);
        File file;
        InputStream inputStream = new FileInputStream(filePath);
        PutStreamObject(s3client, bucketName, key, inputStream, contentType);

        //s3client.listObjectsV2("xxx.log");
        //System.out.println(111);

        System.out.println(s3client.getUrl(bucketName, key));

        //GeneratePresignedURL(s3client, bucketName, key);

        //deleteObject(s3client, bucketName, key);


        //GeneratePresignedURL(s3client, "xxx.log", "testPic.png");


    }

    private static void GeneratePresignedURL(AmazonS3 s3client, String bucketName, String objectKey) {

        try {
            // 设置URL有效时间为1h
            java.util.Date expiration = new java.util.Date();
            long expTimeMillis = expiration.getTime();
            expTimeMillis += 1000 * 60 * 60;
            expiration.setTime(expTimeMillis);

            // 生成URL
            System.out.println("Generating pre-signed URL.");
            GeneratePresignedUrlRequest generatePresignedUrlRequest =
                    new GeneratePresignedUrlRequest(bucketName, objectKey)
                            .withMethod(HttpMethod.GET)
                            .withExpiration(expiration);

            URL url = s3client.generatePresignedUrl(generatePresignedUrlRequest);
            System.out.println("Pre-Signed URL: " + url.toString());
        } catch (SdkClientException e) {
            e.printStackTrace();
        }
    }

    private static void putObject(AmazonS3 s3client, String bucketName, String key, String filePath, String contentType) {
        XskyS3Bucket xskyS3Bucket = new XskyS3Bucket(s3client);
        System.out.println(xskyS3Bucket.ListBuckets());


        PutObjectResult putResult = null;
        //创建用户自定义元数据
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.addUserMetadata("user", "test");
        metadata.setContentType(contentType);

        //创建上传文件请求（PutObjectRequest）
        PutObjectRequest putRequest = new PutObjectRequest(bucketName, key, new File(filePath));
        putRequest.setMetadata(metadata);
        putRequest.withCannedAcl(CannedAccessControlList.PublicRead);
        try {
            //调用putObject上传文件
            putResult = s3client.putObject(putRequest);
        } catch (AmazonServiceException ase) {
            System.out.println("Caught an AmazonServiceException when put object of\"" + key + "\".");
            System.out.println("Error Message: " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code: " + ase.getErrorCode());
            System.out.println("Error Type: " + ase.getErrorType());
            System.out.println("Request ID: " + ase.getRequestId());
            System.exit(1);
        }
        System.out.println(putResult);
    }

    public static PutObjectResult PutStreamObject(AmazonS3 s3client,String bucketName, String key, InputStream inputStream, String contentType) {
        //初始化上传文件流
        PutObjectResult putResult = null;
        //创建用户自定义元数据
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.addUserMetadata("bucketName", bucketName);
        metadata.addUserMetadata("key", key);
        if (StringUtils.isNotBlank(contentType)) {
            metadata.setContentType(contentType);
        }

        //创建上传文件请求（PutObjectRequest）
        PutObjectRequest putRequest = new PutObjectRequest(bucketName, key, inputStream, metadata);
        putRequest.withCannedAcl(CannedAccessControlList.PublicRead);
        try {
            putResult = s3client.putObject(putRequest);
        } catch (AmazonServiceException ase) {
            System.out.println("Caught an AmazonServiceException when put object of" + key + ".");
            System.out.println("Error Message: " + ase.getMessage());

            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code: " + ase.getErrorCode());
            System.out.println("Error Type: " + ase.getErrorType());
            System.out.println("Request ID: " + ase.getRequestId());
            System.exit(1);
        }
        return putResult;
    }


    private static void deleteObject(AmazonS3 s3client, String bucketName, String objectKey) {
        try {
            s3client.deleteObject(bucketName, objectKey);
        } catch (AmazonServiceException ase) {
            System.out.println("Error Message: " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code: " + ase.getErrorCode());
            System.out.println("Error Type: " + ase.getErrorType());
            System.out.println("Request ID: " + ase.getRequestId());
            System.exit(1);
        }
    }
}
